<template>
  <div class="main">
    <a-spin :spinning="loading">
    <a-form class="user-layout-login" ref="formLogin" :form="form" id="formLogin">

      <a-form-item>
        <a-input
          size="large"
          v-decorator="['username',validatorRules.username,{ validator: {} }]"
          type="text"
          tabindex="1"
          @focusin="focusInputCode('focusout')"
          placeholder="请输入帐户名">
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-item>

      <a-form-item>
        <a-input
          v-decorator="['password',validatorRules.password]"
          tabindex="2"
          size="large"
          type="password"
          autocomplete="false"
          @focusin="focusInputCode('focusout')"
          placeholder="请输入密码">
          <a-icon slot="prefix" type="lock"  :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-item>

          <a-row :gutter="0">
            <a-col :span="16">
              <a-form-item style="margin-bottom: 10px">
                <a-input
                  v-decorator="['inputCode',validatorRules.inputCode]"
                  size="large"
                  type="text"
                  tabindex="3"
                  @focusin="focusInputCode('focusin')"
                  @change="inputCodeChange"
                  placeholder="请输入验证码">
<!--                  <a-icon slot="prefix" v-if=" inputCodeContent==verifiedCode " type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>-->
<!--                  <a-icon slot="prefix" v-else type="frown" :style="{ color: 'rgba(0,0,0,.25)' }"/>-->
                  <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
            </a-col>
<!--            <a-col  :span="10"  v-show="inputCodeShowFg">-->
<!--              <j-graphic-code @success="generateCode" ref="jgraphicCodeRef" style="float: right" remote></j-graphic-code>-->
<!--            </a-col>-->
            <a-col :span="8" style="text-align: right"  v-show="inputCodeShowFg">
              <img v-if="requestCodeSuccess" style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
              <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
              <!--<j-graphic-code @success="generateCode" ref="jgraphicCodeRef" style="float: right" remote></j-graphic-code>-->
            </a-col>
          </a-row>
      <a-form-item style="margin-bottom: 14px">
        <!--<a-checkbox v-decorator="['rememberMe', {initialValue: true, valuePropName: 'checked'}]" >自动登陆</a-checkbox>-->
        <!--

        <router-link :to="{ name: 'alteration', params: {} }" class="forge-password" style="float: right;">
          忘记密码
        </router-link>-->
      </a-form-item>

      <a-form-item style="margin-top:14px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="loginBtn"
          @click.stop.prevent="handleSubmit"
          :disabled="loginBtn">确定
        </a-button>
      </a-form-item>

     <!-- <div class="user-login-other">
        <span>其他登录方式</span>
        <a><a-icon class="item-icon" type="alipay-circle"></a-icon></a>
        <a><a-icon class="item-icon" type="taobao-circle"></a-icon></a>
        <a><a-icon class="item-icon" type="weibo-circle"></a-icon></a>
        <router-link class="register" :to="{ name: 'register' }">
          注册账户
        </router-link>
      </div>-->
    </a-form>

    <login-modal ref="showloginModal" @ok="modalFormOk" @close="close"></login-modal>
    </a-spin>
  </div>
</template>

  <script>
  //import md5 from "md5"
  import { mapActions } from "vuex"
  import { timeFix } from "@lone/lone-vue/src/utils/util"
  import Vue from 'vue'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import loginModal from './modules/LoginModal'
  import JGraphicCode from '@lone/lone-vue/src/components/jeecg/JGraphicCode'
  import {  putAction,postAction,getAction } from '@lone/lone-vue/src/api/manage'
  import { encryption , getEncryptedString } from '@lone/lone-vue/src/utils/encryption/aesEncrypt'
  import store from '@/store/'
  import { USER_INFO } from "@/store/mutation-types"

  export default {
    components: {
      JGraphicCode,
      loginModal
    },
    data () {
      return {
        customActiveKey: "tab1",
        LoneDevice:`${window._CONFIG['LoneDevice']}`,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        requiredTwoStepCaptcha: false,
        stepCaptchaVisible: false,
        loading:false,
        inputCodeShowFg:false,
        form: this.$form.createForm(this),
        state: {
          time: 60,
          smsSendBtn: false,
        },
        formLogin: {
          username: "",
          password: "",
          captcha: "",
          mobile: "",
          rememberMe: true
        },
        validatorRules: {
          username:{rules: [{ required: true, message: '请输入用户名!',validator: 'click'}]},
          password:{rules: [{ required: true, message: '请输入密码!',validator: 'click'}]},
          mobile:{rules: [{validator:this.validateMobile}]},
          captcha:{rule: [{ required: true, message: '请输入验证码!'}]},
          inputCode:{rules: [{ required: true, message: '请输入验证码!'}]}
          // inputCode:{rules: [{ required: true, message: '请输入验证码!'},{validator: this.validateInputCode}]}
        },
        verifiedCode:"",
        inputCodeContent:"",
        inputCodeNull:true,

        departList:[],
        departVisible:false,
        departSelected:"",
        currentUsername:"",
        validate_status:"",
        currdatetime:'',
        randCodeImage:'',
        requestCodeSuccess:false,
        url: {
          queryRoleByUserId :"/sys/queryRoleByUserId",
        },
      }
    },
    created () {
      this.currdatetime = new Date().getTime();
      Vue.ls.remove(ACCESS_TOKEN)
      this.getRouterData();
      this.handleChangeCheckCode();
      // update-begin- --- author:scott ------ date:20190225 ---- for:暂时注释，未实现登录验证码功能
//      this.$http.get('/auth/2step-code')
//        .then(res => {
//          this.requiredTwoStepCaptcha = res.result.stepCode
//        }).catch(err => {
//          console.log('2step-code:', err)
//        })
      // update-end- --- author:scott ------ date:20190225 ---- for:暂时注释，未实现登录验证码功能
     // this.requiredTwoStepCaptcha = true
      let accessToken = this.$route.params.XAccessToken;
      if (accessToken && accessToken != "") {
        let acceptLone = `${window._CONFIG['LoneSSO']}`;
        if (!acceptLone) {
          acceptLone = 'sso';
        }
        this.handleSSOLogin(accessToken,acceptLone);
      } else {

      }
    },
    methods: {
      ...mapActions([ "Login", "Logout" ]),
      // 角色选择窗口确定
      modalFormOk(role){
        let that = this
        this.loginParams.roleId = role.roleId
        this.loginParams.departId = role.departId;
        this.loginParams.departName = role.departName;
        this.loginParams.roleName = role.roleName;
        this.loginParams.device =this.LoneDevice;
        that.Login(this.loginParams).then(() => {
          that.loginSuccess();
        }).catch((err) => {
          that.requestFailed(err);
        })
      },
      // 单点登录处理
      handleSSOLogin (accessToken, accessLone) {
        this.loading = true;
        let that = this
        let loginParams = {
          remember_me: that.formLogin.rememberMe
        };
        loginParams['accessToken'] = accessToken;
        loginParams['accessLone'] = accessLone;
        // 验证token有效性
        if (accessLone == 'sso') {
          that.loginBtn = true
          getAction('/sys/commonApi/validateLogin',{'accessToken': accessToken}).then((res)=>{
            this.loading = false;
            if(res.success){
              loginParams['username'] = res.result.username;

              // 使用token登录
              that.loginParams = loginParams;
              that.loginParams.device =that.LoneDevice;
              that.loginBtn = true
              postAction('/sys/queryRoleByUserId',that.loginParams).then((res)=>{
                this.loading = false;
                if(res.success){
                  that.loginParams['username'] = res.attributes.username;
                  if(res.result.length===1){
                    that.modalFormOk(res.result[0]);
                  }else{
                    that.$refs.showloginModal.showUserRole(res.result);
                  }
                }else{
                  that.close();
                  that.requestFailed(res);
                }
              });
            }else{
              that.requestFailed(res);
              return;
            }
          });
        } else {
          // 使用token登录
          that.loginParams = loginParams;
          that.loginParams.device =this.LoneDevice;
          that.loginBtn = true
          postAction('/sys/queryRoleByUserId',that.loginParams).then((res)=>{
            that.loading = false;
            if(res.success){
              that.loginParams['username'] = res.attributes.username;
              if(res.result.length===1){
                that.modalFormOk(res.result[0]);
              }else{
                that.$refs.showloginModal.showUserRole(res.result);
              }
            }else{
              that.close();
              that.requestFailed(res);
            }
          });
        }


      },
      // handler登录按钮
      handleSubmit () {
        let that = this
        let flag = false

        let loginParams = {
          remember_me: that.formLogin.rememberMe
        };

        // 使用账户密码登陆
        that.form.validateFields([ 'username', 'password','inputCode', 'rememberMe' ], { force: true }, (err, values) => {
          if (!err) {
            flag = true
            loginParams.device =that.LoneDevice;
            loginParams.username = values.username
            // update-begin- --- author:scott ------ date:20190805 ---- for:密码加密逻辑暂时注释掉，有点问题
            //loginParams.password = md5(values.password)
            //loginParams.password = encryption(values.password,that.encryptedString.key,that.encryptedString.iv)
            loginParams.password = values.password
            loginParams.remember_me = values.rememberMe
            // update-begin- --- author:scott ------ date:20190805 ---- for:密码加密逻辑暂时注释掉，有点问题
            // let checkParams = this.$refs.jgraphicCodeRef.getLoginParam()
            // loginParams.captcha = checkParams.checkCode
            // loginParams.checkKey = checkParams.checkKey

            loginParams.captcha = that.inputCodeContent
            loginParams.checkKey = that.currdatetime

            this.username = values.username;
          }
        })
        this.loginParams = loginParams;
        if (!flag) return
        that.loginBtn = true
        postAction('/sys/queryRoleByUserId',loginParams).then((res)=>{
          if(res.success){
            if(res.result.length===1){
              this.modalFormOk(res.result[0]);
            }else{
              this.$refs.showloginModal.showUserRole(res.result);
            }
          }else{
            that.close();
            this.requestFailed(res);
          }
        });
      },
      handleChangeCheckCode(){
        this.currdatetime = new Date().getTime();
        getAction(`/sys/randomImage/${this.currdatetime}`).then(res=>{
          if(res.success){
            this.randCodeImage = res.result
            this.requestCodeSuccess=true
          }else{
            this.$message.error(res.message)
            this.requestCodeSuccess=false
          }
        }).catch(()=>{
          this.requestCodeSuccess=false
        })
      },
      close(){
        this.loginBtn=false;
        this.form.resetFields("inputCode");
      },
      loginSuccess () {
        this.loginBtn = false
        this.$router.push({ name: "dashboard" })
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`,
        });
      },
      requestFailed (err) {
        this.$notification[ 'error' ]({
          message: '登录失败',
          description: ((err.response || {}).data || {}).message || err.message || "请求出现错误，请稍后再试",
          duration: 4,
        });
        this.loginBtn = false;
      },
      validateMobile(rule,value,callback){
        if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)){
          callback();
        }else{
          callback("您的手机号码格式不正确!");
        }

      },
      validateInputCode(rule,value,callback){
        if(!value || this.verifiedCode==this.inputCodeContent){
          callback();
        }else{
          callback("您输入的验证码不正确!");
        }
      },
      generateCode(value){
        this.verifiedCode = value.toLowerCase()
      },
      inputCodeChange(e){
        this.inputCodeContent = e.target.value
        // if(!e.target.value||0==e.target.value){
        //   this.inputCodeNull=true
        // }else{
        //   this.inputCodeContent = this.inputCodeContent.toLowerCase()
        //   this.inputCodeNull=false
        // }
      },
      focusInputCode(type) {
        if (type == "focusin") {
          this.inputCodeShowFg= true;
          // this.$refs.jgraphicCodeRef.reloadPic();
        } else {
          this.inputCodeShowFg = false;
        }
      },
      getRouterData(){
        this.$nextTick(() => {
          if (this.$route.params.username) {
            this.form.setFieldsValue({
              'username': this.$route.params.username
            });
          }
        })
      },
      //获取密码加密规则
      getEncrypte(){
        var encryptedString = Vue.ls.get(ENCRYPTED_STRING);
        if(encryptedString == null){
          getEncryptedString().then((data) => {
            this.encryptedString = data
          });
        }else{
          this.encryptedString = encryptedString;
        }
      },

    }
  }
</script>

<style lang="less" scoped>

  .user-layout-login {
    label {
      font-size: 14px;
    }

    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

    .forge-password {
      font-size: 14px;
    }

    button.login-button {
      padding: 0 15px;
      font-size: 16px;
      height: 40px;
      width: 100%;
    }

    .user-login-other {
      text-align: left;
      margin-top: 24px;
      line-height: 22px;

      .item-icon {
        font-size: 24px;
        color: rgba(0,0,0,.2);
        margin-left: 16px;
        vertical-align: middle;
        cursor: pointer;
        transition: color .3s;

        &:hover {
          color: #1890ff;
        }
      }

      .register {
        float: right;
      }
    }
  }

</style>
<style>
  .valid-error .ant-select-selection__placeholder{
    color: #f5222d;
  }
</style>